import React, { useEffect } from 'react';
import { Space, Button, DatePicker } from 'antd';
import _ from 'lodash';
import moment from 'moment';

import { useTRState, TjStation, TjSelect } from '@/pages/ETrade/components';
import { getSettlementClassDetailType } from './services';

const defaultForm = (power) => ({
  dates: [moment().startOf('year'), moment().endOf('year')],
  stationIdList: _.flattenDeep(
    power.map((x) => x?.children.map((y) => y?.children.map((z) => z.value))),
  ),
});

export default ({ power, onChange = () => {} }) => {
  const [state, setState] = useTRState({
    // 表单
    ...defaultForm(power),
    regionItem: null,
    tradeTypeCode1Id: [], // 交易类型1
    tradeTypeCode2Id: [], // 交易类型2
    opts1: [], // 多选
    opts2: [], // 多选与1联动
    opts2All: [], // 全部类型2，有父级标识pid
    isQuery: '',
  });

  useEffect(() => {
    power?.[0] && onChangeRegion(power[0], 'init');
  }, [power]);

  React.useEffect(() => {
    if (state.isQuery !== '') {
      _onFinish();
    }
  }, [state.isQuery]);

  const fetchOptions = async (marketId, t) => {
    const res = await getSettlementClassDetailType(marketId);
    if (res && res.data) {
      const opts1 = _.get(res.data, 'attributesOne', []);
      const opts2 = _.get(res.data, 'attributesTwo', []);
      const tradeTypeCode1Id = opts1.map((x) => x.value);
      const tradeTypeCode2Id = opts2.map((x) => x.value);
      setState({
        opts1,
        opts2,
        tradeTypeCode1Id,
        tradeTypeCode2Id,
      });
      if (t === 'init') {
        setState({
          isQuery: new Date().valueOf(),
        });
      }
    }
  };

  /** methods */

  const onChangeRegion = (regionItem, t) => {
    // 切换省份,全选交易单元
    const list = regionItem?.children || [];
    const stations = _.flatten(list.map(({ children }) => children));
    const stationIdList = stations.map((x) => x.value);
    state.regionItem = regionItem;
    state.stationIdList = [...stationIdList];
    setState({
      regionItem,
      stationIdList,
    });
    t === 'search' && _onFinish();
    (t === 'init' || t === 'change') && fetchOptions(regionItem.marketId, t);
  };

  const _onFinish = () => {
    // 查询
    const { stationIdList, tradeTypeCode1Id, tradeTypeCode2Id, dates, regionItem } = state;
    const params = {
      marketId: regionItem.marketId,
      startDate: dates[0].format('YYYY-MM'),
      endDate: dates[1].format('YYYY-MM'),
      stationIdList,
      tradeTypeCode1Id,
      tradeTypeCode2Id,
    };
    onChange?.(params);
  };

  const _onReset = () => {
    // 重置&查询
    let { dates, stationIdList } = defaultForm(power);
    state.dates = dates;
    state.stationIdList = stationIdList;
    const tradeTypeCode1Id = state.opts1.map((x) => x.value);
    const tradeTypeCode2Id = state.opts2.map((x) => x.value);
    setState({
      dates,
      stationIdList,
      tradeTypeCode1Id,
      tradeTypeCode2Id,
    });
    onChangeRegion(power[0], 'init');
  };

  return (
    <Space size={16} wrap>
      <TjSelect
        style={{ width: 160 }}
        value={state.regionItem?.value}
        options={power}
        showSearch
        onChange={(v, opt) => onChangeRegion(opt, 'change')}
      />
      <TjStation
        value={state.stationIdList}
        options={state.regionItem?.children || []}
        onChange={(stationIdList) => setState({ stationIdList })}
      />
      <DatePicker.RangePicker
        style={{ width: 256 }}
        value={state.dates}
        picker="month"
        separator="-"
        format={'YYYYMM'}
        allowClear={false}
        onChange={(dates) => setState({ dates })}
      />
      <TjSelect
        value={state.tradeTypeCode1Id}
        options={state.opts1}
        onChange={(tradeTypeCode1Id) => setState({ tradeTypeCode1Id })}
        mode="multiple"
        label="交易类型1"
        style={{ width: 200 }}
      />
      <TjSelect
        value={state.tradeTypeCode2Id}
        options={state.opts2}
        onChange={(tradeTypeCode2Id) => setState({ tradeTypeCode2Id })}
        mode="multiple"
        label="交易类型2"
        style={{ width: 200 }}
      />
      <Space size={16}>
        <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
          查询
        </Button>
        <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
          重置
        </Button>
      </Space>
    </Space>
  );
};
